package cn.edu.thu.laud.com.utils;

import java.io.IOException;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class XMLParser {

	private Element root;


	public XMLParser(String file) {

		try {
			SAXBuilder builder = new SAXBuilder();
			Document doc;
			doc = builder.build(XMLParser.class.getResourceAsStream(file));
			//doc=builder.build(new File(file));
			root = doc.getRootElement();

		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	public int getDefaultSystemThreadNumber(){
		return Integer.valueOf(root.getChildText("DefaultSystemThreadNumber"));
	}
	public String getServerIp() {
		// this.serverip = root.getAttributeValue("ServerIP");
		return root.getChildText("ServerIP").toString();
	}

	public int getServerPort() {
		// this.serverip = root.getAttributeValue("ServerIP");
		return Integer.valueOf(root.getChildText("ServerPort"));
	}
	public String getDatabaseIp() {
		return root.getChildText("DatabaseIP");
	}

	public int getDatabasePort() {
		return Integer.parseInt(root.getChildText("DatabasePort"));
	}

	public String getDatabaseName() {
		return root.getChildText("DatabaseName");
	}
	public String getDataServerIp(){
		return root.getChildText("DataServerIP").toString();
	}
	public int getDataServerPort(){
		return Integer.valueOf(root.getChildText("DataServerPort"));
	}
	public String getIndexImplement(String indexType){
		Element indexImpl=root.getChild("IndexImplement");
		return indexImpl.getChildTextTrim(indexType);
	}
	public String getFunctionImplement(String functionName){
		Element indexImpl=root.getChild("IndexImplement");
		return indexImpl.getChildTextTrim(functionName);
	}
	
//	public Map<String,String> getIndexs(){
//		Element e= root.getChild("IndexImplement");
//		Map<String,String> indexs=new HashMap<String,String>();
//		for(Object ee:e.getChildren()){
//			indexs.put(((Element)ee).getName(),((Element)ee).getTextTrim());
//		}
//		return indexs;
//	}
	public String getElementString(String name,Object defaultVale){
		String element=root.getChildText(name);
		if(element==null)
			return defaultVale.toString();
		else return element.toString();
	}
	public Element getElement(String name){
		return root.getChild(name);
	}
	public static void main(String[]s){
		XMLParser parser=new XMLParser("conf/laud.xml");
		;
		for(Object obj:parser.getElement("IndexRelation").getChildren()){
			System.out.println(((Element)obj).getAttributeValue("order"));
			System.out.println(((Element)obj).getName());
			System.out.println(((Element)obj).getText());
			System.out.println("-----------");		
		}
	}
}
